package cn.edu.whu.forecast.service.impl;

import cn.edu.whu.forecast.entity.mysql.SectionFlowWaterLevel;
import cn.edu.whu.forecast.mapper.mysql.SectionFlowWaterLevelMapper;
import cn.edu.whu.forecast.service.SectionService;
import cn.edu.whu.forecast.vo.response.DistrictWaterLevelAndFlowForecastVo;
import cn.edu.whu.forecast.vo.response.WaterLevelAndFlowForecastVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service("SectionServiceImpl")
public class SectionServiceImpl implements SectionService {
    @Resource
    private SectionFlowWaterLevelMapper sectionFlowWaterLevelMapper;
    @Override
    public void addFlowWaterLevel(SectionFlowWaterLevel sectionFlowWaterLevel) {
        sectionFlowWaterLevelMapper.insertSelective(sectionFlowWaterLevel);
    }

    @Override
    public DistrictWaterLevelAndFlowForecastVo getWaterLevelAndFlowForecastByTimeAndDistrict(LocalDateTime time, Integer sectionId) {
        HashMap<Integer, String> map = new HashMap<>();
        map.put(92,"C");
        map.put(58,"E");
        map.put(13,"G");
        map.put(2,"J");
        map.put(119,"A+B");
        map.put(91,"D");
        map.put(69,"F");
        map.put(55,"H");
        map.put(12,"I");
        LocalDateTime endTime = time.plusHours(9);
        List<SectionFlowWaterLevel> forecasts = sectionFlowWaterLevelMapper.getWaterLevelAndFlowForecastByTimeAndDistrict(time, endTime, sectionId);
        DistrictWaterLevelAndFlowForecastVo districtWaterLevelAndFlowForecastVo = new DistrictWaterLevelAndFlowForecastVo();
        List<WaterLevelAndFlowForecastVo> list = new ArrayList<>();
        for(SectionFlowWaterLevel sectionFlowWaterLevel : forecasts){
            WaterLevelAndFlowForecastVo waterLevelAndFlowForecastVo = new WaterLevelAndFlowForecastVo();
            waterLevelAndFlowForecastVo.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(Date.from(time.atZone(ZoneId.systemDefault()).toInstant())));
            waterLevelAndFlowForecastVo.setFlow(sectionFlowWaterLevel.getFlow().setScale(2, BigDecimal.ROUND_HALF_UP));
            waterLevelAndFlowForecastVo.setWaterLevel(sectionFlowWaterLevel.getWaterLevel().setScale(2,BigDecimal.ROUND_HALF_UP));
            list.add(waterLevelAndFlowForecastVo);
            time = time.plusHours(1);
        }
        districtWaterLevelAndFlowForecastVo.setDistrictName(map.get(sectionId));
        districtWaterLevelAndFlowForecastVo.setDateList(list);

        return districtWaterLevelAndFlowForecastVo;
    }
}
